<template>
  <div ref="codeEditRef">
  </div>
</template>

<script>
import ace from "ace-builds";
import {useTheme} from "@/hooks/useTheme.ts";
import "./importAll.ts" // 导入ace所有依赖
export default {
  name:"CodeEdit",
  props:{
    modelValue:{
      type:String,
      default:''
    },
    // 外部传入的语法类型
    language: {
      type: String,
      default: "json",
    },
  },
  watch:{
    modelValue(newProps){
      if(this.codeEdit){
        //解决光标移动问题
        const position = this.codeEdit.getCursorPosition();
        this.codeEdit.getSession().setValue(newProps);
        this.codeEdit.clearSelection();
        this.codeEdit.moveCursorToPosition(position);
      }
    },
    language(){
      this.setOptions()
    },
    importTheme(){
      this.setOptions()
    }
  },
  data(){
    return{
      codeEdit:null,
    }
  },
  computed:{
    importLanguage(){
      return 'mode-'+this.language
    },
    activeThemeName() {
      return useTheme().activeThemeName.value
    },
    theme() {
      if(this.activeThemeName==='normal') {
        return 'textmate'
      }else if(this.activeThemeName === 'dark') {
        return 'gruvbox_dark_hard'
      } else if(this.activeThemeName === 'dark-blue') {
        return 'tomorrow_night_blue'
      }
    },
    importTheme(){
      return 'theme-'+this.theme
    },
  },
  mounted() {
    this.codeEdit = ace.edit(this.$refs.codeEditRef,{
      tabSize: 2,
      showPrintMargin: false,
      fontSize: 14,
      useWorker: true,
    })
    this.setOptions()
    this.codeEdit.getSession().setUseWrapMode(true);
    this.codeEdit.on("change",()=>{
      this.$emit('update:modelValue',this.codeEdit.getValue())
    })
    //快捷键
    this.codeEdit.commands.addCommand({
      name: 'formatter',
      bindKey: { win: 'Ctrl-Shift-F', mac: 'Command-Shift-F' },
      exec: () => this.formatterCode()
    })
    this.codeEdit.setValue(this.modelValue);
  },
  methods:{
    setOptions(){
      this.codeEdit.setOptions({
        theme: "ace/theme/" + (this.theme),
        mode: "ace/mode/" + (this.language),
        wrap: true,
      })
    },
    formatterCode() {
      this.$emit('formatter', this.codeEdit)
    }
  },
  beforeDestroy() {
    if(this.codeEdit){
      this.codeEdit.destroy()
    }
  }
}
</script>

<style scoped lang="scss">
</style>
